export const FIRST_CATEGORY = '一级类目'
export const SECOND_CATEGORY = '二级类目'
import * as feishuService from '@/api/service/FeishuService'

let categoryData = <any>[];

/**
 * 表格列表
 */
export function categories(): Promise<any> {
  const tableId = globalThis.tableConfig.category
  return new Promise((resolve) => {
    (async () => {
      if(!categoryData || categoryData.length === 0){
        const items = <any>[];

        for await (const page of await feishuService.appTableRecords(tableId, null, 100)) {
          items.push(...page.items)
        }
        const arr: string[] = []
        const childMap = {}
        items.forEach((item: any) => {
          const level1 = item.fields[FIRST_CATEGORY] as string
          const level2 = item.fields[SECOND_CATEGORY] as string
          if (!arr.includes(level1)) {
            arr.push(level1);
          }
          const children = childMap[level1] ? childMap[level1] : [];
          children.push(level2)
          childMap[level1] = children
        })
        categoryData = arr.map((item: any) => {
          const children = childMap[item] ? childMap[item].map(item => {
            return {
              id: item,
              name: item
            }
          }) : []
          return {
            id: item,
            name: item,
            children: children
          }
        })

        }


      resolve(categoryData)
    })()
  })
}
